package com.iot08.api.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.iot08.api.config.redis.RedisClusterService;
import com.iot08.api.service.supplement.KafkaService;
import com.iot08.api.utils.request.ParamHandle;
import com.iot08.api.vo.request.DelDeviceCostFlowReqVO;
import com.iot08.api.vo.request.TypeParamReqVO;
import com.iot08.api.vo.request.base.BaseAccountReqVO;
import com.iot08.common.constant.Const;
import com.iot08.common.constant.ConstCacheField;
import com.iot08.common.constant.ConstKafka;
import com.iot08.common.entity.app.Account;
import com.iot08.common.entity.app.Device;
import com.iot08.common.entity.app.DeviceCostFlow;
import com.iot08.common.service.base.BaseService;
import com.iot08.common.utils.DateUtil;
import com.iot08.common.utils.StringUtil;
import com.iot08.common.utils.response.ResponseEnum;
import com.iot08.common.utils.response.ResponseMap;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;

/**
 * @version 1.0
 * @Description:
 * @author: Rock
 * @time: 2020/12/15 11:00
 */
@Slf4j
@Service
public class DeviceCostFlowService extends BaseService<DeviceCostFlow> {

    @Resource
    private DeviceService deviceService;
    @Resource
    private AccountService accountService;
    @Resource
    private KafkaService kafkaService;
    @Resource
    private RedisClusterService redisClusterService;

    /**
     * 话费和流量查询指令
     *
     * @param imei
     * @param vo
     * @time: 2020/12/15 10:44
     * @author: Rock
     * @version 1.0
     */
    public ResponseMap inquireTraffic(String imei, TypeParamReqVO vo) {
        Device device = deviceService.findById(imei);
        if (device == null) {
            log.error("Device is null. _id={}", imei);
            return ResponseMap.fail(ResponseEnum.STATUS2001.getCode(), ResponseEnum.STATUS2001.getMsg(), imei);
        }
        String onlineStatus = redisClusterService.hget(imei, ConstCacheField.ONLINE_STATUS);
        if (!"1".equals(onlineStatus)) {
            return ResponseMap.fail(ResponseEnum.STATUS5001.getCode(), ResponseEnum.STATUS5001.getMsg());
        }
        /*String content = "";
        String phone = "";
        if (Const.INT_1.equals(vo.getType())) {
            content = "YE";
        } else {
            content = "CXLL";
        }
        if (Const.INT_0.equals(device.getNetworkOperator())) {
            //移动
            phone = "10086";
        } else if (Const.INT_1.equals(device.getNetworkOperator())) {
            //联通
            phone = "10010";
        } else {
            //电信
            phone = "10001";
            if (Const.INT_1.equals(vo.getType())) {
                content = "102";
            } else {
                content = "108";
            }
        }*/
        // 发送kafka
        JSONObject data = new JSONObject();
        //data.put("inquire", vo.getType());
        data.put("phone", vo.getPhone());
        data.put("openid", vo.getOpenid());
        data.put("content", vo.getContent().replace(" ",""));
        kafkaService.emitDeviceDemand(imei, ConstKafka.DEVICE_TYPE_Inquire, data, vo.getOpenid());
        return ResponseMap.success();
    }

    /**
     * 查询话费流量的记录
     *
     * @param imei
     * @param vo
     * @time: 2020/12/15 11:24
     * @author: Rock
     * @version 1.0
     */
    public ResponseMap list(String imei, BaseAccountReqVO vo) {
        Account account = accountService.findById(vo.getOpenid());
        if (account == null) {
            log.error("Account is null. _id={}", imei);
            return ResponseMap.fail(ResponseEnum.STATUS2000.getCode(), ResponseEnum.STATUS2000.getMsg());
        }
        Double deleteCostTime = 0d;
        if (account.getDeleteCostTime() != null) {
            deleteCostTime = account.getDeleteCostTime();
        }
        List<Object> data = new ArrayList<>();
        Query query = new Query(Criteria.where("i").is(imei));
        query.with(Sort.by(Sort.Order.desc("_id")));
        List<DeviceCostFlow> list = this.find(query);
        for (DeviceCostFlow costFlow : list) {
            Map<String, Object> temp = new HashMap<>();
            if (costFlow.getTime() != null && costFlow.getTime() > deleteCostTime) {
                temp.put("id", costFlow.getId());
                temp.put("content", costFlow.getContent());
                temp.put("timestamp", costFlow.getTime());
                //添加到列表
                data.add(temp);
            }
        }
        ResponseMap res = ResponseMap.success();
        res.put("messages", data);
        return res;
    }

    /**
     * 删除话费流量的记录
     *
     * @param imei
     * @param vo
     * @time: 2021/1/13 10:24
     * @author: Rock
     * @version 1.0
     */
    public ResponseMap del(String imei, DelDeviceCostFlowReqVO vo) {
        if (StringUtil.isBlank(vo.getMessageIds())) {
            //删除全部
            Update updateAccount = new Update();
            updateAccount.set("delete_cost_time", DateUtil.nowTimestampToLong());
            accountService.updateById(vo.getOpenid(), updateAccount);
        } else {
            JSONArray idArr = JSON.parseArray(vo.getMessageIds());
            //删除指定id
            Set<ObjectId> objectIdList = new HashSet<>();
            for (int i = 0; i < idArr.size(); i++) {
                if (ObjectId.isValid(idArr.getString(i))) {
                    objectIdList.add(new ObjectId(idArr.getString(i)));
                }
            }
            if (objectIdList.size() > 0) {
                this.delByIds(objectIdList);
            }
        }
        return ResponseMap.success();
    }

    /**
     * @param deviceCostFlow
     * @time: 2021/1/22 11:34
     * @author: Rock
     * @version 1.0
     */
    @Override
    public DeviceCostFlow save(DeviceCostFlow deviceCostFlow) {
        //所有记录的失效时间天数 3个月
        deviceCostFlow.setTime(DateUtil.nowTimestampToDouble());
        deviceCostFlow.setExpiryAt(DateUtil.getSystemExpiryAt());
        return mongoTemplate.save(deviceCostFlow);
    }
}
